package filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.Globals;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;

import pku.ss.movieSystem.common.Constants;

public class AuthenticationFilter implements Filter {
	
	private String onErrorUrl;
	private FilterConfig filterConfig;

	public void destroy() {
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
	
		HttpServletRequest httpRequest = (HttpServletRequest)arg0;		
		HttpServletResponse httpResponse=(HttpServletResponse)arg1; // Current session	
		HttpSession httpSession = httpRequest.getSession();
		
		String url = httpRequest.getRequestURI();
		boolean canPassWithoutAu = false;
		
		for(String urlStr : Constants.FREELY_ACCESS) {
			if(url.indexOf(urlStr)>0)
				canPassWithoutAu = true;
		}
		
		if(url.equals("/movieSystem/"))
			canPassWithoutAu = true;
		
		if(canPassWithoutAu) {
			arg2.doFilter(arg0,arg1);
		}
		else {
			if (httpSession.getAttribute("user") == null)		
			{	
				System.out.println("not exist");
				ActionErrors errors=new ActionErrors();		
				errors.add(ActionErrors.GLOBAL_MESSAGE,new ActionError("error authentication"));	
				httpRequest.setAttribute(Globals.ERROR_KEY,errors);		
				httpRequest.getRequestDispatcher(onErrorUrl).forward(httpRequest,httpResponse);		
			}else
			{
				System.out.println("exist");
				//httpRequest.getRequestDispatcher("index.jsp").forward(httpRequest, httpResponse);
				arg2.doFilter(arg0,arg1);
				
			}
		}
	}

	public void init(FilterConfig arg0) throws ServletException {
		
		filterConfig = arg0;
		onErrorUrl=filterConfig.getInitParameter("onError");
		if(onErrorUrl==null || "".equals(onErrorUrl))
		{
			onErrorUrl="userLogin.jsp";
		}
	}



}
